from sqlalchemy import Column, Integer, String, Text, Float, ForeignKey, Boolean, DateTime, JSON
from sqlalchemy.orm import relationship
from datetime import datetime
from commons.database import Base


class Product(Base):
    """产品表模型，存储商品信息"""
    __tablename__ = "products"

    id = Column(Integer, primary_key=True, autoincrement=True, comment="产品ID")
    seller_id = Column(Integer, ForeignKey('users.id'), nullable=False, comment="卖家ID")
    name = Column(String(100), nullable=False, comment="产品名称")
    cover_image = Column(String(200), nullable=False, comment="产品封面图路径")
    category_id = Column(Integer, ForeignKey('categories.id'), nullable=False, comment="产品分类ID")
    description = Column(Text, comment="产品详情")
    price = Column(Float, nullable=False, comment="产品价格")
    is_active = Column(Boolean, default=True, comment="是否上架")
    created_at = Column(DateTime, default=datetime.utcnow, comment="创建时间")
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment="更新时间")
    bank_account_name = Column(String(100), comment="银行账户名称")
    bank_account_number = Column(String(50), comment="银行账号")
    payment_instructions = Column(Text, comment="支付说明")
    detail_images = Column(JSON, comment="详情图片路径列表")

    # 定义关系
    seller = relationship("User", backref="products")
    category = relationship("Category", backref="products")
    orders = relationship("OrderItem", back_populates="product")

    def to_dict(self):
        """将产品对象转换为字典"""
        return {
            "id": self.id,
            "seller_id": self.seller_id,
            "name": self.name,
            "cover_image": self.cover_image,
            "category_id": self.category_id,
            "description": self.description,
            "price": self.price,
            "is_active": self.is_active,
            "created_at": self.created_at.strftime("%Y-%m-%d %H:%M:%S") if self.created_at else None,
            "updated_at": self.updated_at.strftime("%Y-%m-%d %H:%M:%S") if self.updated_at else None,
            "bank_account_name": self.bank_account_name,
            "bank_account_number": self.bank_account_number,
            "payment_instructions": self.payment_instructions,
            "detail_images": self.detail_images
        }